<!-- invoicing.thtml -->
<?php
$cashierCanEdit = ($current_user['auth_type'] == AUTH_ADMIN || $current_user['auth_type'] == AUTH_CASH);
$sel = array('producers-' . $producer['Producer']['producer_id'] => 'This Invoice');
$df = '%B %e, %Y';
?>
<h1>Invoice for the order cycle of
<?php
	echo strftime($df,strtotime($del['Delivery']['order_open'])), ' - ', strftime($df,strtotime($del['Delivery']['order_closed'] . ' -1 day'));
	if (isset($neighbors['prev'])) {
		echo ' ', $html->link('[Previous Cycle]', '/producers/invoicing/'. $producer['Producer']['producer_id'] . '/' . $sorting[0][0] . '/' . $neighbors['prev']['Delivery']['delivery_id']);
	}
	if (isset($neighbors['next'])) {
		echo ' ', $html->link('[Next Cycle]', '/producers/invoicing/'. $producer['Producer']['producer_id'] . '/' . $sorting[0][0] . '/' . $neighbors['next']['Delivery']['delivery_id']);
	}

?>
</h1>
<h2>All Orders by <?=ucwords($sorting[0][0]), ' ', $html->link('[pdf]','/producers/invoicing/'. $producer['Producer']['producer_id'] . '/' . $sorting[0][0] . '/' . $del['Delivery']['delivery_id'] . '.pdf')?></h2>
<h3><?=$producer['Producer']['business_name'];?></h3>
<div class="breadcrumbs">
<p>View By: <?=$html->link(ucwords($sorting[1][0]), '/producers/invoicing/'. $producer['Producer']['producer_id'] . '/' . $sorting[1][0] . '/' . $del['Delivery']['delivery_id'])?> | <?=$html->link(ucwords($sorting[0][0]), '/producers/invoicing/'. $producer['Producer']['producer_id'] . '/' . $sorting[0][0] . '/' . $del['Delivery']['delivery_id'])?></p>
</div>
<?php

$mtime = strtotime($producer['Member']['paid_fee'] . ' +' . Configure::read('Membership.valid_for'));
$ptime = strtotime(date('r', $mtime) . ' -' . Configure::read('Membership.ask_for_fee'));
$now = time();
$due = strftime($df,$mtime);
$member_message = '';
if ($now > $mtime) {
  $member_message = 'Your membership fee of $' . $producer['Member']['memb_amt_owed'] . ' is due as of ' . $due . '.  Your total is adjusted below.';
} else if ($now > $ptime) {
  $member_message = 'Your membership fee of $' . $producer['Member']['memb_amt_owed'] . ' will be due '. $due . '.  Your total is adjusted below, but we can waive it for this invoice if you prefer.';
}else {
  $member_message = 'Your membership is paid through ' . $due . '.';
}
$m_fee = (time() > $ptime) ? $producer['Member']['memb_amt_owed'] : 0;
?>
<p><?=$member_message;?></p>
<table>
<tr><th><?=ucwords($sorting[1][0])?></th><th>Qty.</th><th>Price/Unit</th><th>Weight (est)</th><th>Tax</th><th>Total</th></tr>
<?php
if ($sorting[0][0] == 'product') { $sorting[0][0] = 'product_list'; }
else { $sorting[1][0] = 'product_list'; }

$p = '';
$m = '';
$r_total = 0;
$q_total = 0;
$subTotal = 0;
$taxTotal = 0;
$contact = '';
foreach ($lines as $line) {
	
  $comp = $line[$sorting[0][0]][$sorting[0][1]];
  if ($sorting[0][0]=='member') {
    $comp = $line[$sorting[0][0]][$sorting[0][1]] . ', ' . $line['member']['first_name'];
    }
  if ($p != $comp) {
    if ($r_total > 0) {
      echo '<tr><td class="subtotal" colspan="2">Quantity Total: ' . $q_total . '<td class="subtotal" colspan="4">' . $p . $contact . ' Total: $' . number_format($r_total,2) . '</td></tr>' . "\n";
      $r_total = 0;
      $q_total = 0;
    }
    $p = $comp;
    $contact = ($sorting[0][0]=='member') ? ' - Phone: ' . $line['member']['home_phone'] . ' Email: <a href="mailto:' . $line['member']['email_address'] . '">' .  $line['member']['email_address'] . '</a>' : '';
  
    echo '<tr><th colspan="6">' . $p . '</th></tr>' . "\n";
  }
  
	//calculate weight
	if ($line['basket_items']['weight'] == 0) {
		if ($line['product_list']['random_weight'] != 0) {
			if ($line['product_list']['minimum_weight'] == 0 && $line['product_list']['maximum_weight'] == 0) { // weights should not be averaged
				$line['basket_items']['weight'] = 1;
			} else {
				$line['basket_items']['weight'] = ($line['product_list']['minimum_weight'] + $line['product_list']['maximum_weight']) / 2;
			}
		}
	}
	//calculate total
	$line['total'] = ($line['basket_items']['missing']) ? 0 : $line['orderables']['price'] * $line['basket_items']['quantity'];
	$line['total'] = ($line['basket_items']['weight'] == 0) ? $line['total'] : $line['total'] * $line['basket_items']['weight'];
	$line['tax'] = ($line['product_list']['tax_exempt']) ? 0 : $line['total'] * SALES_TAX;
	$m_comp = ($sorting[1][0] == 'member') ? $line[$sorting[1][0]][$sorting[1][1]] . ', ' . $line['member']['first_name'] : $line[$sorting[1][0]][$sorting[1][1]];
	
	if (($m != $m_comp) || ($r_total == 0)) {
		$m = ($sorting[1][0] == 'member') ? $line[$sorting[1][0]][$sorting[1][1]] . ', ' . $line['member']['first_name']  : $line[$sorting[1][0]][$sorting[1][1]];
	}
	
  $w = ($line['basket_items']['weight'] == 0) ? 'N/A' : number_format($line['basket_items']['weight'],2) . ' ' . $line['orderables']['priced_by'] . '(s)';
  $q = ($line['basket_items']['missing']) ? 0 : $line['basket_items']['quantity'];
  echo '<td>';
  
  if ($line['basket_items']['missing']) {
   echo '<em>' . $m . '</em>';
  } else {
   echo $m;
  }
  
  echo '</td>';
  echo '<td>' . $q . '</td>';
  echo '<td>$' . number_format($line['orderables']['price'],2) . '/' . $line['orderables']['priced_by'] . '</td>';
  echo '<td>' . $w . '</td>';
  echo '<td>$' . number_format($line['tax'],2) . "</td>";
  echo '<td>$' . number_format($line['total']+$line['tax'],2) . "</td></tr>\n";
	$tot = round($line['total']*100);
	$tax = round($line['tax']*100);
  $r_total += ($tot+$tax)/100;
	$subTotal += $tot;
	$taxTotal += $tax;
	$q_total += $q;
}
//$contact = ' - Phone: ' . $line['member']['home_phone'] . ' Email: ' . $line['member']['email_address'];
echo '<tr><td class="subtotal" colspan="2">Quantity Total: ' . $q_total . '<td class="subtotal" colspan="4">' . $p . $contact . ' Total: $' . number_format($r_total,2) . '</td></tr>' . "\n";
$surcharge = round($subTotal * (PROD_SURCHARGE/100))/100;
$total = ($subTotal/100) - $surcharge + ($taxTotal/100);
?>
</table>
<?php

if ($cashierCanEdit) {
	e('<input type="submit" value="Save Basket"/></form>');
}
$adjTotal = 0;
foreach($notes as $note) {
	$tstring = ($note['Note']['adj_tax']) ? ' + Tax' : '';
	echo '<p><strong>Note from ', $note['From']['username'], ':</strong> ', $note['Note']['text'], ' Adjustment: $', number_format($note['Note']['adj_amount'], 2), $tstring, '</p>';
	if ($note['Note']['adj_tax']) {
		$taxTotal += round($note['Note']['adj_amount'] * SALES_TAX * 100);
	}
	if ($cashierCanEdit) {
		e($html->link('[Remove Note]', '/producers/removeNote/' . $note['Note']['id'] . '/' . $producer['Producer']['producer_id']));
	}
	$adjTotal += $note['Note']['adj_amount'] * 100;
}

//$total = round(($total) * 100)/100;
$surcharge = round((MEMB_SURCHARGE/100) * $subTotal);
$total = (($subTotal + $adjTotal - $surcharge + $taxTotal)/100);

?>
<p>Sub-Total: $<?=number_format($subTotal/100,2)?></p>
<p>Coop Surcharge (<?=MEMB_SURCHARGE?>%):- $<?=number_format($surcharge/100,2)?></p>
<p>Membership Fee: - $<?=number_format($m_fee,2)?></p>
<p>Adjustments Total: $<?=number_format($adjTotal/100,2)?></p>
<p>Sales Tax: $<?=number_format($taxTotal/100,2)?></p>
<p>Total: $<?=number_format($total - $m_fee,2)?></p>
<?php

if ($cashierCanEdit) {
	$nl = "\n";
	echo '<fieldset>', $nl;
	echo '<legend>Add Note to Invoice</legend>', $nl;
	echo '<form id="addNote" action="', $html->url('/producers/invoicing/' . $producer['Producer']['producer_id']),'" method="POST">', $nl;
	//echo $html->hidden('Note/table_name', array('value'=>'members')), $nl;
	//echo $html->hidden('Note/table_id', array('value'=>$member['Member']['member_id'])), $nl;
	
	
	echo $form->hidden('Note.from_id', array('value'=>$current_user['member_id'])), $nl;
	echo $form->hidden('Note.delivery_id', array('value'=>$current_delivery)), $nl;
	
	echo $form->input('Note.table',array('label' => 'Regarding', 'options' => $sel, 'value'=>'producers-' . $producer['Producer']['producer_id'])), $nl;
	echo $form->input('Note.text', array('label' => 'Note', 'rows'=>'5', 'cols' => '50')), $nl;
	echo $form->input('Note.adj_amount', array('label' => 'Adjustment', 'value' => '0.00', 'class' => 'quantity')), $nl;
	echo $form->input('Note.adj_tax', array('type' => 'checkbox', 'label' => 'Apply Tax')), $nl;
	echo $form->submit('Add Note'), $nl;
	echo '</form>', $nl;
	echo '</fieldset>', $nl;
}
?>
